package s02;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName ServerTCP
 * @Description 服务端实现
 * @Author Li
 * @Date 2022/8/13 10:08
 * @ModifyDate 2022/8/13 10:08
 * @Version 1.0
 */
public class ServerTCP {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器启动，等待连接...");
        // 1.创建ServerSocket对象，绑定端口，开始等待连接
        ServerSocket server = new ServerSocket(6666);
        // 2.接收连接accept方法，返回socket对象
        Socket socket = server.accept();
        // 3.通过socket获取输入流
        InputStream is = socket.getInputStream();
        // 4.一次性读取数据
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        String msg = new String(bytes, 0, len);
        System.out.println(msg);
        // =========回写数据========
        // 5.通过socket获取输出流
        OutputStream os = socket.getOutputStream();
        // 6.回写数据
        os.write("我是服务器回写的！！！".getBytes());
        // 7.关闭资源
        os.close();
        is.close();
        server.close();
    }
}
